package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.dto.PageInfo;
import com.itheima.ydd.pojo.SysRole;
import com.itheima.ydd.pojo.SysUser;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.service.SysRoleService;
import com.itheima.ydd.service.SysUserService;
import com.itheima.ydd.utils.AdminCheak;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/sys_user")
@Slf4j
public class SysUserController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;

    /**
     * 后台管理员用户的分页查询
     * 前端显示sys_role表的管理员名字,而不是标号,而SysUser没有这个成员,
     * 这就表明需要dto类了
     *
     * @param loginName
     * @param status
     * @param phone
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<R> list(@RequestParam("login_name") String loginName,
                                  @RequestParam(value = "status", defaultValue = "3") int status,
                                  String phone, int page, int limit) {
        //创建分页Page类
        Page<SysUser> userPage = new Page<>(page, limit);
        //模糊查询
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(loginName != null, SysUser::getLoginName, loginName);
        wrapper.like(status != 3, SysUser::getStatus, status);
        wrapper.like(phone != null, SysUser::getPhone, phone);
        //排序方式
        wrapper.orderByDesc(SysUser::getUpdateDate);
        //查询到的,先放入page
        Page<SysUser> sysUserPage = userService.page(userPage, wrapper);
        Page<SysUserDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(sysUserPage, dtoPage, "records");
        List<SysUser> records = sysUserPage.getRecords();
        List<SysUserDto> sysUserDtos = new ArrayList<>();
        for (SysUser record : records) {
            SysUserDto dto = new SysUserDto();
            BeanUtils.copyProperties(record, dto);
            List<String> roleIds = getStringRoleIds(record);
            dto.setRoleIdList(roleIds);
            List<String> list = new ArrayList<>();
            for (String roleId : roleIds) {
                SysRole sysRole = roleService.getById(roleId);
                list.add(sysRole.getName());
            }
            dto.setRolenmae(list);
            sysUserDtos.add(dto);

        }
        dtoPage.setRecords(sysUserDtos);
        PageInfo<SysUserDto> pageInfo = new PageInfo<>();
        pageInfo.setCount((int) dtoPage.getTotal());
        pageInfo.setTotalPages((int) dtoPage.getPages());
        pageInfo.setPageSize((int) dtoPage.getSize());
        pageInfo.setCurrentPage((int) dtoPage.getCurrent());
        pageInfo.setData(dtoPage.getRecords());
        return ResponseEntity.ok(R.success(pageInfo));
    }

    /**
     * 用于封装多个roleId
     *
     * @param user
     * @return
     */
    private List<String> getStringRoleIds(SysUser user) {
        //查询用户角色id集合: roleIdList
        String[] roleIds = user.getRoleId().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> roleIdList = new ArrayList<>();
        Collections.addAll(roleIdList, roleIds);
        return roleIdList;
    }

    /**
     * 根据id删除,但是不能删除admin
     * 这里还没有对登录用户进行校验,查看是否有权限
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResponseEntity<R> delete(String id) {

        //if (id.equals("1")) return ResponseEntity.ok(R.err("删除失败,管理员不能删除"));
        userService.removeById(id);
        return ResponseEntity.ok(R.success("删除成功"));
    }

    /**
     * 添加管理员
     *通过方法重载,把roleid设置上
     * @param sysUser
     * @return
     */
    @PostMapping("/add")
    public ResponseEntity<R> add(@RequestBody SysUserDto sysUser) {
        getStringRoleIds(sysUser);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        boolean save = userService.save(sysUser);

        return save ? ResponseEntity.ok(R.success("添加成功")) : ResponseEntity.ok(R.err("添加失败"));
    }

    /**
     * 根据id查询用户,用于数据的回显
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResponseEntity<R> rowInfo(String id) {
        SysUser byId = userService.getById(id);
        SysUserDto dto = new SysUserDto();
        BeanUtils.copyProperties(byId, dto);
        dto.setRoleIdList(getStringRoleIds(byId));
        return ResponseEntity.ok(R.success(dto));
    }

    /**
     * 根据传入对象修改
     *先判断rolelist是否被改变,如果改了,要重新给roleid赋值
     * @param dto
     * @return
     */
    @PostMapping("/update")
    public ResponseEntity<R> update(@RequestBody SysUserDto dto) {
        if (dto.getRoleIdList()!=null){
            getStringRoleIds(dto);
        }
        boolean flag = userService.updateById(dto);
        return flag ? ResponseEntity.ok(R.success("修改成功")) : ResponseEntity.ok(R.err("修改失败"));
    }

    /**
     *
     * @param dto
     */
    private void getStringRoleIds(@RequestBody SysUserDto dto) {

        StringBuilder sb = new StringBuilder();
        List<String> roleIdList = dto.getRoleIdList();
        sb.append("[");
        for (int i = 0; i < roleIdList.size(); i++) {
            String roleId = roleIdList.get(i);
            sb.append("\"").append(roleId).append("\"").append(i == roleIdList.size() - 1 ? "" : ",");
        }
        sb.append("]");
        dto.setRoleId(sb.toString());
    }

}
